package com.crazy.multids.config.common;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 切换数据源拦截器
 *
 * @author crazyhu@wezhuiyi.com
 * @date 2018-09-16 13:26
 **/
@Aspect
public class DataSourceInterceptor implements Ordered {

    @Override
    public int getOrder() {
        // 小于启动类上的@EnableTransactionManagement#order 属性即可
        return 1;
    }

    @Around(value = "@annotation(dds)")
    public Object proceed(ProceedingJoinPoint pjp, DynaminDataSource dds) throws Throwable {
        if (dds.value() == DataSourceEnum.READ) {
            DataSourceContextHolder.setRead();
        } else {
            DataSourceContextHolder.setWrite();
        }
        try {
            return pjp.proceed();
        } finally {
            DataSourceContextHolder.clear();
        }
    }
}
